<?php

function getConnection(){

    $dbms = 'mysql';
    $host = '127.0.0.1';
    $dbname = 'pubweb';
    $user = 'zzn';
    $password = '123456';
    $dsn = "$dbms:host=$host;dbname=$dbname";

    $pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_INIT_COMMAND => "set names utf8mb4"));

    return $pdo;
}

function updateToken($pdo, $id, $token)
{
    $stm = $pdo->prepare("select * from token_data where uid = ?");
    $stm->bindParam(1, $id);
    $stm->execute();
    $result = $stm->fetchAll();
    if (count($result) == 0) {
        $stm = $pdo->prepare("insert into token_data values (?,?)");
        $stm->bindParam(1, $id);
        $stm->bindParam(2, $token);
        $stm->execute();
    } else {
        $stm = $pdo->prepare("update token_data set token = ? where uid = ?");
        $stm->bindParam(1, $token);
        $stm->bindParam(2, $id);
        $stm->execute();

    }

}

function checkToken($pdo,$uid){
    $headers = getallheaders();
    $jwt = @$headers['Authorization'];
    if (empty($jwt)){
        return false;
    }
    $stm = $pdo->prepare("select token from token_data where uid = ?");
    $stm->bindParam(1,$uid);
    $stm->execute();
    $result = $stm->fetchAll();
    $token = $result[0]['token'];
    if ($jwt == $token){
        return true;
    }else{
        echo $jwt.'<=front===end=>'.$token;
        return false;
    }
}

function return_result($arr)
{
    echo json_encode($arr);
}

function clearCache(){
    $arr = array('shared'=>0,'chats'=>array());
    writeRes($arr);
}

function readRes(){
    $filename = 'resource.json';
    $f = fopen($filename,'r');
    $cache = fread($f,filesize($filename));
    fclose($f);
    return json_decode($cache);
}

function writeRes($array){
    $filename = 'resource.json';
    $f = fopen($filename,'w');
    fwrite($f,json_encode($array));
    fclose($f);
    return true;
}

function reverseArr($arr){
    $b = array();
    for ($i = count($arr)-1;$i>=0;$i--){
        $b[count($arr) - $i -1] = $arr[$i];
    }
    return $b;

}